package edu.hunau.cxb19.oop.class21.hk;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-03-24 14:52:49
 */
public class HomeWorkTest {
	
	@Test
	public void testSort() {
		String datas="wersfaafafasfwfsfsdfsfsdfssssss";
		
		Map<Character, Integer> counter = counter(datas);
		List<Entry<Character, Integer>> list = sortMap(counter);
		for (Entry<Character, Integer> entry : list) {
			System.out.println(entry.getKey()+" : "+entry.getValue());
		}
		
	}
  
	public List<Map.Entry<Character, Integer>> sortMap(Map<Character, Integer> datas) {
		//set集合不会记录顺序
		Set<Entry<Character, Integer>> entrySet = datas.entrySet();
		// 将一个Set集合转成List集合。
		List<Map.Entry<Character, Integer>> list = new ArrayList<>(entrySet);
		// 通过Collections.sort对集合进行排序
//		Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
//			public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
//				return  o2.getValue()-o1.getValue();
//			}
//
//		});
		//Collections.sort(List,Comparator);
		 Collections.sort(list,(o1,o2)->o2.getValue()-o1.getValue());

		return list;
	}

	/**
	 * 统计字符串中字符出现的次数
	 * 
	 * @param datas
	 * @return
	 */
	public Map<Character, Integer> counter(String datas) {
		Map<Character, Integer> maps = new HashMap<>();
		for (int i = 0; i < datas.length(); i++) {
			char c = datas.charAt(i);
			// 判定map中作为key的c是否出现过
			/*
			 * if (maps.containsKey(c)) { maps.put(c, maps.get(c) + 1); } else { maps.put(c,
			 * 1); }
			 */
			Integer counter = maps.get(c);
			counter = counter == null ? 1 : counter + 1;
			maps.put(c, counter);
		}
		return maps;
	}

}
